/**
 * @Title: simpleCharts_directive.js
 * @Description: 简单chart
 * Copyright: Copyright (c) 2014 
 * Company:中国平安
 *
 * @Project HIMS-FWA
 * @author QIANDUO875
 * @date 2014年9月29日 上午9:10:51
 * @version V1.0
 */
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.directives');
	app.directive('fwaCharts',['$timeout',function($timeout){
		
		var defaultOption = {
			legend: null,
			toolbox:{show:false},
			calculable:false,
			grid:{
				x:20,
				y:20,
				x2:20,
				y2:20,
				borderColor:'#eee'
			},
			tooltip : {
		        trigger: 'axis'
			},
			yAxis : [{
				type : 'value',
				axisLine:{
					show:true,
					lineStyle:{
						color: '#eee', width: 1, type: 'solid'
					}
				}
	        }],
	        xAxis : [{
	        	axisLine:{
					show:true,
					lineStyle:{
						color: '#eee', width: 1, type: 'solid'
					}
				},
	            type : 'value'
	        }],
	        color:['#dd4814','#006397','#3ca5d0','#86d3e4','#aaa'],
	        series:[]
		};
		
		function compile(tElement, tAttrs, transclude) {
			return function($scope, $elem, $attrs){
				var chart = echarts.init($elem.get(0)),
					option = $scope.$parent.$eval($attrs.option) || {},
					timeoutPromis = null;
				
				function setOption() {
					option = $.extend(true,{},defaultOption,option);
					chart.clear();
					try{
						chart.setOption(option);
					}catch(error) {}
					chart.resize();
				}
				
				$scope.$parent.$watchCollection($attrs.option+'.series', function(series,o){
					if(!series || series.length==0) {
						series = [{name:'',type:'bar',data:[]}];
					}
					option.series = series;
					chart.setSeries(option.series, true);
				});
				
				$scope.$parent.$watchCollection($attrs.option+'.xAxis', function(n,o){
					if(n && n.length>0 && (!n[0].data || n[0].data.length ==0)) {
						n[0].data = null;
					}
					option.xAxis = n;
					setOption();
				});
				
				$scope.$parent.$watchCollection($attrs.option+'.legend', function(n,o){
					option.legend = n;
					setOption();
				});
				$scope.$parent.$watchCollection($attrs.option+'.title', function(n,o){
					option.title = n;
					setOption();
				});
				setOption();
				
				$(window).on('resize', function(){
					if(timeoutPromis) {
						$timeout.cancel(timeoutPromis);
					}
					timeoutPromis = $timeout(function(){
						chart.resize();
					}, 200);
				});
			}
		}
		
		return {
			restrict: 'E',
			scope:true,
			replace:true,
			template:'<div></div>',
			compile:compile
		};
		
		
	}]);
	
})();